# Copyright (c) 2025 Huawei Technologies Co. Ltd.
# deepinsight is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#          http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the Mulan PSL v2 for more details.
import os
from abc import ABC, abstractmethod
from starlette.requests import HTTPConnection


class AuthProvider(ABC):
    """认证提供者接口，所有认证方式都需要实现这些方法"""

    @abstractmethod
    async def verify_credentials(self, request: HTTPConnection) -> bool:
        """验证请求中的凭证是否有效"""
        pass

    @abstractmethod
    async def get_user_id(self, request: HTTPConnection) -> str:
        """从请求中获取用户ID"""
        pass


class AuthManager:
    """认证管理器，用于获取配置的认证提供者"""
    _providers = {}

    @classmethod
    def register_provider(cls, name: str, provider_class):
        """注册认证提供者"""
        if issubclass(provider_class, AuthProvider):
            cls._providers[name] = provider_class
        else:
            raise ValueError(f"Provider {provider_class} does not implement AuthProvider interface")

    @classmethod
    def get_provider(cls, name: str = None) -> AuthProvider:
        """获取指定的或默认的认证提供者"""
        # 从环境变量获取配置的认证方式，默认使用openeuler_intelligence
        auth_type = name or os.getenv("AUTH_PROVIDER", "openeuler_intelligence")

        provider_class = cls._providers.get(auth_type)
        if not provider_class:
            raise ValueError(f"No auth provider registered for {auth_type}")

        return provider_class()
